﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace MovieBrowser.Util
{
    [RunInstaller(true)]
    public partial class InstallDb : Installer
    {
        public InstallDb()
        {
            InitializeComponent();
        }

        [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)]
        public override void Install(IDictionary stateSaver)
        {
            base.Install(stateSaver);

            var c = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location);
            var section = (ConnectionStringsSection)c.GetSection("connectionStrings");
            var path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
           
            
            string datasource = string.Format(@"metadata=res://*/MovieDb.csdl|res://*/MovieDb.ssdl|res://*/MovieDb.msl;provider=System.Data.SQLite;provider connection string='data source={0}\MaxInc\Db\MovieDb.sqlite'", path);
            section.ConnectionStrings["MovieDbEntities"].ConnectionString = datasource;

            var group = c.SectionGroups[@"userSettings"];
            var clientSection = group.Sections["MovieBrowser.Properties.Settings"] as ClientSettingsSection;
            // find setting element
            SettingElement settingElement = null;
            foreach (SettingElement s in clientSection.Settings)
            {
                if (s.Name == "ImdbRules")
                {
                    settingElement = s;
                    break;
                }
            }
            // remove the current value
            clientSection.Settings.Remove(settingElement);

            // change the value
            settingElement.Value.ValueXml.InnerText = path + @"\MaxInc\Db\imdb_re.xml";

            // add the setting
            clientSection.Settings.Add(settingElement);

            c.Save();

            Properties.Settings.Default.ImdbRules = path + "\\imdb_re.xml";
            Properties.Settings.Default.Save();
        }


        [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)]
        public override void Commit(IDictionary savedState)
        {
            base.Commit(savedState);
        }
    }
}
